import { ArrowDown } from '@nutui/icons-react-taro'
import { Button, Collapse, Input } from '@nutui/nutui-react-taro'
import { Image, ScrollView, Text, View } from '@tarojs/components'
import React, { useMemo, useState } from 'react'
import { Controller, useForm } from 'react-hook-form'
import { useRequest } from 'taro-hooks'
import FeeDetails from '../../components/fee-details'
import Layout from '../../components/layout'
import PackageCard from '../../components/package-card'
import SelectionModal from '../../components/selection-modal'
import SelectionSection from '../../components/selection-section'
import { THEME_COLORS } from '../../constants'
import { useCustomization, useMaterialSelection, useNavigation, usePackageQuotation } from '../../hooks'
import { getMaterial, getProductInfo, obtainColorThemes, obtainStyles, updateSnapShot } from '../../services/product'
import './index.less'

// 接口定义
interface SpaceSize {
  building: number | string
  interior: number | string
}

const PackageSelection: React.FC = () => {
  // 表单实例
  const { navigateTo, params } = useNavigation()
  const projectId = params?.projectId || ''
  const snapShotId = params?.snapShotId || ''
  const packageId = params?.packageId || ''

  // 使用 react-hook-form
  const {
    control,
    handleSubmit: handleFormSubmit,
    setValue,
  } = useForm<{
    [key: string]: number // key 为 subCategory.title, value 为 materialId
  }>({
    defaultValues: {},
  })

  // 使用定制 Hook 管理材料定制
  const { customizedMaterials, selectedCustomization, processCustomization } = useCustomization()

  // 获取 产品信息
  const { data: productInfoData, loading: productInfoDataLoading } = useRequest(getProductInfo, {
    defaultParams: [{ productId: projectId, snapShotId: snapShotId, packageId: packageId }],
    onSuccess(data) {
      setSelectedStyle(data?.product.style.id)
      setSelectedColor(data?.product.colorScheme.id)
      setSpaceSize({ building: data?.product.buildSize || 0, interior: data?.product.spaceSize || 0 })
    },
  })

  // 获取 材料
  const { runAsync: getMaterialAsync, data: materialData } = useRequest(getMaterial, {
    manual: true,
    onSuccess(result, requestParams) {
      if (result?.categories.subCategories && productInfoData?.product.packageMaterials) {
        const categoryId = requestParams[0]?.categoryId

        result.categories.subCategories.forEach((subCategory) => {
          // 优先级1: 检查用户是否已经定制过该类别
          const customized = categoryId ? customizedMaterials[categoryId] : null
          let selectedMaterialId: number | null = null

          if (customized) {
            // 如果用户已定制过，使用用户的选择
            const customizedSubCat = customized.subCategories.find((sc) => sc.id === subCategory.id)
            if (customizedSubCat) {
              selectedMaterialId = customizedSubCat.material.id
            }
          }

          // 优先级2: 如果用户没有定制过，从 packageMaterials 中查找套餐默认材料
          if (!selectedMaterialId) {
            for (const category of productInfoData.product.packageMaterials.categories) {
              const matchedSubCategory = category.subCategories.find((sc) => sc.id === subCategory.id)
              if (matchedSubCategory && matchedSubCategory.materials && matchedSubCategory.materials.length > 0) {
                // 找到了匹配的子类别，使用其第一个材料作为默认选中
                selectedMaterialId = matchedSubCategory.materials[0].id
                break
              }
            }
          }

          // 优先级3: 如果在 packageMaterials 中也没有找到，则使用可选材料的第一个
          if (!selectedMaterialId && subCategory.materials && subCategory.materials.length > 0) {
            selectedMaterialId = subCategory.materials[0].id
          }

          // 设置表单值
          if (selectedMaterialId) {
            setValue(subCategory.id + '', selectedMaterialId)
          }
        })
      }
    },
  })

  // 获取风格数据
  const { data: stylesData } = useRequest(obtainStyles)

  // 获取色彩方案数据 - 添加 cacheKey 防止重复请求
  const { data: colorSchemesData } = useRequest(obtainColorThemes)
  const { runAsync: updateSnapShotAsync } = useRequest(updateSnapShot, { manual: true })

  const [selectedColor, setSelectedColor] = useState<number>()
  const [selectedStyle, setSelectedStyle] = useState<number>()
  const [spaceSize, setSpaceSize] = useState<SpaceSize>({
    building: 0,
    interior: 0,
  })
  // 模态框状态
  const [showStyleModal, setShowStyleModal] = useState<boolean>(false)
  const [showSizeModal, setShowSizeModal] = useState<boolean>(false)
  const [showColorModal, setShowColorModal] = useState<boolean>(false)
  const [showCustomizationModal, setShowCustomizationModal] = useState<boolean>(false)

  // 定制相关状态
  const [materialKey, setMaterialKey] = useState<string>('')
  const [showCategoryCustomizeButtons, setShowCategoryCustomizeButtons] = useState<boolean>(false)

  // 处理风格和色彩数据
  const styles = useMemo(() => stylesData?.styles || [], [stylesData])
  const colorSchemes = useMemo(() => colorSchemesData?.colorSchemes || [], [colorSchemesData])

  // 获取当前选择的风格和色彩
  const currentStyle = useMemo(() => styles.find((s) => s.id === selectedStyle), [selectedStyle, styles])

  const currentColorScheme = useMemo(
    () => colorSchemes.find((c) => c.id === selectedColor),
    [colorSchemes, selectedColor],
  )

  // 使用材料选择 Hook 管理最终材料选择
  const { materialIdsForApi } = useMaterialSelection({
    productInfoData,
    selectedCustomization,
  })

  // 使用费用计算 Hook 管理套餐报价
  const packageQuotation = usePackageQuotation({
    productInfoData,
    customizedMaterials,
    showCategoryCustomizeButtons,
  })

  // 事件处理
  const handleStyleSelect = (styleId: number) => {
    setSelectedStyle(styleId)
    setShowStyleModal(false)
  }

  const handleColorSelect = (colorId: number) => {
    setSelectedColor(colorId)
    setShowColorModal(false)
  }

  const handleSizeChange = (field: 'building' | 'interior', value: string) => {
    setSpaceSize((prev) => ({ ...prev, [field]: value }))
  }

  // 表单提交
  const handleSubmit = () => {
    updateSnapShotAsync({
      productId: Number(projectId),
      buildSize: Number(spaceSize.building),
      styleId: selectedStyle as number,
      colorSchemeId: selectedColor as number,
      materialIds: materialIdsForApi,
    })
      .then((res) => {
        const newSnapShotId = res.snapshot.id
        navigateTo({ url: `/pages/fee-estimation/index?snapShotId=${newSnapShotId}&packageId=${packageId}` })
      })
      .catch((error) => {
        console.error('更新快照失败:', error)
      })
  }

  // 处理总"去定制"按钮点击
  const handleMainCustomizeClick = () => {
    setShowCategoryCustomizeButtons(true)
  }

  // 处理类目定制按钮点击
  const handleCategoryCustomize = (key: string) => {
    setMaterialKey(key)
    setShowCustomizationModal(true)
  }

  const onCustomizationSubmit = handleFormSubmit((data) => {
    // 使用 Hook 处理定制提交
    processCustomization(materialData, materialKey, data)
    setShowCustomizationModal(false)
  })

  return (
    <Layout
      showTabBar={false}
      title='套餐选择'
      loading={productInfoDataLoading}
      footer={
        <View className='p-16'>
          <Button type='primary' block onClick={() => handleSubmit()}>
            确认选择
          </Button>
        </View>
      }>
      <ScrollView className='package-selection-wrapper' scrollY>
        {/* 1. 风格选择 */}
        <SelectionSection title='风格选择' onModify={() => setShowStyleModal(true)}>
          <View className='style-info'>
            <Image className='style-image' src={currentStyle?.image || ''} mode='aspectFill' />
            <View className='style-details'>
              <Text className='style-name'>{currentStyle?.name}</Text>
              <Text className='style-description'>{currentStyle?.description}</Text>
            </View>
          </View>
        </SelectionSection>

        {/* 2. 色彩方案 */}
        <SelectionSection title='色彩方案' onModify={() => setShowColorModal(true)}>
          <View className='color-scheme'>
            <View className='color-header'>
              <Text className='color-name'>{currentColorScheme?.name}</Text>
            </View>
            <Text className='color-description'>{currentColorScheme?.description}</Text>
            <View className='color-palette'>
              {currentColorScheme?.colors.map((color, index) => (
                <View key={index} className='color-dot' style={{ backgroundColor: color }} />
              ))}
            </View>
          </View>
        </SelectionSection>

        {/* 3. 空间尺寸 */}
        <SelectionSection title='空间尺寸' onModify={() => setShowSizeModal(true)}>
          <View className='space-info'>
            <Text className='space-item'>建筑面积：{spaceSize?.building}m²</Text>
            <Text className='space-item'>套内面积：{spaceSize?.interior}m²</Text>
          </View>
        </SelectionSection>

        {/* 4. 套餐选择 */}
        <SelectionSection title='套餐选择' showModify={false} useCard={false}>
          <View className='package-cards'>
            <View className='package-card selected' style={{ borderColor: THEME_COLORS.primary }}>
              <Image
                className='package-image'
                src='https://images.unsplash.com/photo-1560448204-e02f11c3d0e2?w=400&h=300&fit=crop&crop=center'
                mode='aspectFill'
              />
              <View className='package-content'>
                <Text className='package-name'>定制套餐</Text>
                <Text className='package-description'>根据您的需求定制，包含个性化设计和高级建材。</Text>
              </View>
            </View>
          </View>
        </SelectionSection>

        {/* 5. 项目报价 */}
        <SelectionSection title='项目报价' modifyText='去定制' onModify={() => handleMainCustomizeClick()}>
          <FeeDetails
            loading={productInfoDataLoading}
            showCustomized={showCategoryCustomizeButtons}
            handleCustomizedClick={handleCategoryCustomize}
            showCard={false}
            categories={packageQuotation.categories}
            totalAmount={packageQuotation.total?.toString()}
            title='项目费用明细'
            primaryColor={THEME_COLORS.primary}
            note='*此报价为估算价格，最终价格以实际测量和材料选择为准。'
          />
        </SelectionSection>

        {/* 底部确认按钮 */}
        {/* <View className='bottom-button'>
          <Button
            className='confirm-button'
            style={{
              background: THEME_COLORS.primary,
              color: '#fff',
            }}
            onClick={() => handleSubmit()}>
            确认选择
          </Button>
        </View> */}
      </ScrollView>

      {/* 风格选择模态框 */}
      <SelectionModal
        visible={showStyleModal}
        title='风格选择'
        onClose={() => setShowStyleModal(false)}
        // onConfirm={() => setShowStyleModal(false)}
        scrollDirection='horizontal'>
        <View className='style-options-horizontal'>
          {styles.map((style) => (
            <View
              key={style.id}
              className={`style-option-card ${selectedStyle === style.id ? 'selected' : ''}`}
              onClick={() => handleStyleSelect(style.id)}>
              <View className='style-option-image'>
                <Image src={style.image} mode='aspectFill' className='style-img' />
                {selectedStyle === style.id && (
                  <View className='check-icon' style={{ backgroundColor: THEME_COLORS.primary }}>
                    ✓
                  </View>
                )}
              </View>
              <View className='style-option-content'>
                <Text className='style-option-name'>{style.name}</Text>
                <Text className='style-option-description'>{style.description}</Text>
              </View>
            </View>
          ))}
        </View>
      </SelectionModal>

      {/* 尺寸修改模态框 */}
      <SelectionModal
        visible={showSizeModal}
        title='空间尺寸'
        onClose={() => setShowSizeModal(false)}
        // onConfirm={() => setShowSizeModal(false)}
        // confirmText='确认修改'
        scrollable={false}>
        <View className='size-inputs'>
          <View className='input-group'>
            <Text className='input-label'>建筑面积 (m²)</Text>
            <Input
              className='size-input'
              value={spaceSize?.building + ''}
              onChange={(value) => handleSizeChange('building', value)}
              type='number'
              placeholder='请输入建筑面积'
            />
          </View>
          <View className='input-group'>
            <Text className='input-label'>套内面积 (m²)</Text>
            <Input
              className='size-input'
              value={spaceSize?.interior + ''}
              onChange={(value) => handleSizeChange('interior', value)}
              type='number'
              placeholder='请输入套内面积'
            />
          </View>
        </View>
      </SelectionModal>

      {/* 色彩方案模态框 */}
      <SelectionModal visible={showColorModal} title='色彩方案' onClose={() => setShowColorModal(false)} height='70vh'>
        <View className='color-options'>
          {colorSchemes.map((scheme) => (
            <View
              key={scheme.id}
              className={`color-option ${selectedColor === scheme.id ? 'selected' : ''}`}
              style={{
                borderColor: selectedColor === scheme.id ? THEME_COLORS.primary : '#e5e7eb',
                backgroundColor: selectedColor === scheme.id ? `${THEME_COLORS.primary}10` : '#fff',
              }}
              onClick={() => handleColorSelect(scheme.id)}>
              <View className='color-option-header'>
                <Text className='color-option-name'>{scheme.name}</Text>
              </View>
              <Text className='color-option-description'>{scheme.description}</Text>
              <View className='color-option-palette'>
                {scheme.colors.map((color, index) => (
                  <View key={index} className='color-option-dot' style={{ backgroundColor: color }} />
                ))}
              </View>
            </View>
          ))}
        </View>
      </SelectionModal>

      {/* 类目定制模态框 */}
      <SelectionModal
        visible={showCustomizationModal}
        title={materialData?.categories.categoryName || '材料定制'}
        onClose={() => setShowCustomizationModal(false)}
        onOpen={() => {
          getMaterialAsync({ categoryId: Number(materialKey) })
        }}
        // onConfirm={onCustomizationSubmit}
        // confirmText='确认定制'
        height='90vh'>
        {materialData?.categories.subCategories.map((subCategory) => (
          <Collapse key={subCategory.id} defaultActiveName={[subCategory.id.toString()]} expandIcon={<ArrowDown />}>
            <Collapse.Item key={subCategory.id} title={subCategory.title} name={subCategory.id.toString()}>
              <Controller
                control={control}
                name={subCategory.id + ''}
                render={({ field: { value, onChange } }) => (
                  <ScrollView className='options-scroll' scrollX enableFlex>
                    <View className='options-scroll-content'>
                      {subCategory.materials?.map((material) => {
                        return (
                          <PackageCard
                            value={value}
                            key={material.id}
                            onSelect={(materialId, selected) => {
                              if (selected) {
                                onChange(materialId)
                              } else {
                                onChange(null)
                              }
                            }}
                            package={{
                              id: material.id + '',
                              name: material.name,
                              description: material.description,
                              image: material.image,
                              price: material.price.toString(),
                            }}
                          />
                        )
                      })}
                    </View>
                  </ScrollView>
                )}
              />
            </Collapse.Item>
          </Collapse>
        ))}
      </SelectionModal>
    </Layout>
  )
}

export default PackageSelection
